// Copyright (c) 2024 Flutter Video Thumbnail Plus OHOS Plugin
// Use of this source code is governed by a BSD-style license.

import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_video_thumbnail_plus/flutter_video_thumbnail_plus.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Video Thumbnail Test',
      home: VideoThumbnailDemo(),
    );
  }
}

class VideoThumbnailDemo extends StatefulWidget {
  const VideoThumbnailDemo({super.key});

  @override
  VideoThumbnailDemoState createState() => VideoThumbnailDemoState();
}

class VideoThumbnailDemoState extends State<VideoThumbnailDemo> {
  static const MethodChannel _channel = MethodChannel('flutter_video_thumbnail_plus');
  
  String? _thumbnailPath;
  Uint8List? _thumbnailData;
  String? _selectedVideoPath;
  String? _networkThumbnailPath;
  Uint8List? _networkThumbnailData;
  String _status = 'Select a video to generate thumbnail';
  bool _isLoading = false;
  final TextEditingController _networkUrlController = TextEditingController();

  Future<void> _selectVideo() async {
    try {
      setState(() {
        _isLoading = true;
        _status = 'Selecting video...';
      });
      
      final String? videoPath = await _channel.invokeMethod('selectVideo');
      
      setState(() {
        _isLoading = false;
        if (videoPath != null && videoPath.isNotEmpty) {
          _selectedVideoPath = videoPath;
          _status = 'Video selected: ${videoPath.split('/').last}';
          _thumbnailPath = null;
          _thumbnailData = null;
        } else {
          _status = 'No video selected';
        }
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _status = 'Error selecting video: $e';
      });
    }
  }

  Future<void> _generateThumbnailFile() async {
    if (_selectedVideoPath == null || _selectedVideoPath!.isEmpty) {
      setState(() {
        _status = 'Please select a video first';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _status = 'Generating thumbnail file...';
    });

    try {
      final reqMap = <String, dynamic>{
        'video': _selectedVideoPath!,
        'headers': null,
        'path': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70
      };
      
      final String? thumbnailPath = await _channel.invokeMethod('file', reqMap);
      
      setState(() {
        _thumbnailPath = thumbnailPath;
        _status = thumbnailPath != null ? 'Thumbnail saved to: ${thumbnailPath.split('/').last}' : 'Failed to generate thumbnail';
      });
    } catch (e) {
      setState(() {
        _status = 'Error generating thumbnail: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _generateThumbnailData() async {
    if (_selectedVideoPath == null || _selectedVideoPath!.isEmpty) {
      setState(() {
        _status = 'Please select a video first';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _status = 'Generating thumbnail data...';
    });

    try {
      final reqMap = <String, dynamic>{
        'video': _selectedVideoPath!,
        'headers': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70,
      };
      
      final Uint8List? thumbnailData = await _channel.invokeMethod('data', reqMap);
      
      setState(() {
        _thumbnailData = thumbnailData;
        _status = thumbnailData != null ? 'Thumbnail data generated (${thumbnailData.length} bytes)' : 'Failed to generate thumbnail data';
      });
    } catch (e) {
      setState(() {
        _status = 'Error generating thumbnail data: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _generateNetworkThumbnailFile() async {
    final String networkUrl = _networkUrlController.text.trim();
    if (networkUrl.isEmpty) {
      setState(() {
        _status = 'Please enter a network video URL';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _status = 'Generating network thumbnail file...';
    });

    try {
      final reqMap = <String, dynamic>{
        'video': networkUrl,
        'headers': null,
        'path': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70
      };
      
      final String? thumbnailPath = await _channel.invokeMethod('networkFile', reqMap);
      
      setState(() {
        _networkThumbnailPath = thumbnailPath;
        _status = thumbnailPath != null ? 'Network thumbnail saved to: ${thumbnailPath.split('/').last}' : 'Failed to generate network thumbnail';
      });
    } catch (e) {
      setState(() {
        _status = 'Error generating network thumbnail: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _generateNetworkThumbnailData() async {
    final String networkUrl = _networkUrlController.text.trim();
    if (networkUrl.isEmpty) {
      setState(() {
        _status = 'Please enter a network video URL';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _status = 'Generating network thumbnail data...';
    });

    try {
      final reqMap = <String, dynamic>{
        'video': networkUrl,
        'headers': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70,
      };
      
      final Uint8List? thumbnailData = await _channel.invokeMethod('networkData', reqMap);
      
      setState(() {
        _networkThumbnailData = thumbnailData;
        _status = thumbnailData != null ? 'Network thumbnail data generated (${thumbnailData.length} bytes)' : 'Failed to generate network thumbnail data';
      });
    } catch (e) {
      setState(() {
        _status = 'Error generating network thumbnail data: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 检查是否可以生成缩略图
  bool _canGenerateThumbnail() {
    if (_isLoading) return false;
    
    // 检查是否有本地视频或网络视频URL
    final bool hasLocalVideo = _selectedVideoPath != null && _selectedVideoPath!.isNotEmpty;
    final bool hasNetworkUrl = _networkUrlController.text.trim().isNotEmpty;
    
    return hasLocalVideo || hasNetworkUrl;
  }

  // 统一的缩略图生成方法
  Future<void> _generateThumbnail() async {
    // 清除之前的缩略图
    setState(() {
      _thumbnailPath = null;
      _thumbnailData = null;
      _networkThumbnailPath = null;
      _networkThumbnailData = null;
    });

    // 优先使用本地视频，如果没有则使用网络视频
    final bool hasLocalVideo = _selectedVideoPath != null && _selectedVideoPath!.isNotEmpty;
    final String networkUrl = _networkUrlController.text.trim();
    
    if (hasLocalVideo) {
      // 生成本地视频缩略图（同时生成文件和数据）
      await _generateLocalThumbnails();
    } else if (networkUrl.isNotEmpty) {
      // 生成网络视频缩略图（同时生成文件和数据）
      await _generateNetworkThumbnails();
    }
  }

  // 生成本地视频缩略图
  Future<void> _generateLocalThumbnails() async {
    setState(() {
      _isLoading = true;
      _status = '正在生成本地视频缩略图...';
    });

    try {
      // 同时生成文件和数据
      final reqMapFile = <String, dynamic>{
        'video': _selectedVideoPath!,
        'headers': null,
        'path': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70
      };
      
      final reqMapData = <String, dynamic>{
        'video': _selectedVideoPath!,
        'headers': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70,
      };
      
      final results = await Future.wait([
        _channel.invokeMethod('file', reqMapFile),
        _channel.invokeMethod('data', reqMapData),
      ]);
      
      setState(() {
        _thumbnailPath = results[0] as String?;
        _thumbnailData = results[1] as Uint8List?;
        _status = '本地视频缩略图生成成功';
      });
    } catch (e) {
      setState(() {
        _status = '生成本地视频缩略图失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 生成网络视频缩略图
  Future<void> _generateNetworkThumbnails() async {
    final String networkUrl = _networkUrlController.text.trim();
    
    setState(() {
      _isLoading = true;
      _status = '正在生成网络视频缩略图...';
    });

    try {
      // 同时生成文件和数据
      final reqMapFile = <String, dynamic>{
        'video': networkUrl,
        'headers': null,
        'path': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70
      };
      
      final reqMapData = <String, dynamic>{
        'video': networkUrl,
        'headers': null,
        'format': 0, // JPEG
        'maxh': 200,
        'maxw': 200,
        'timeMs': 1000,
        'quality': 70,
      };
      
      final results = await Future.wait([
        _channel.invokeMethod('networkFile', reqMapFile),
        _channel.invokeMethod('networkData', reqMapData),
      ]);
      
      setState(() {
        _networkThumbnailPath = results[0] as String?;
        _networkThumbnailData = results[1] as Uint8List?;
        _status = '网络视频缩略图生成成功';
      });
    } catch (e) {
      setState(() {
        _status = '生成网络视频缩略图失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _networkUrlController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Video Thumbnail Test'),
        backgroundColor: Colors.blue,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Text(
                      'Status: $_status',
                      style: Theme.of(context).textTheme.bodyMedium,
                      textAlign: TextAlign.center,
                    ),
                    if (_isLoading) ...
                      const [
                        SizedBox(height: 16),
                        CircularProgressIndicator(),
                      ],
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            // 缩略图显示区域
            Container(
              height: 250,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade300),
                borderRadius: BorderRadius.circular(8),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    if (_thumbnailPath != null) ...
                      [
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text('Local Thumbnail File:', style: TextStyle(fontWeight: FontWeight.bold)),
                        ),
                        if (File(_thumbnailPath!).existsSync())
                          Image.file(
                            File(_thumbnailPath!),
                            height: 200,
                            fit: BoxFit.contain,
                          )
                        else
                          const Text('Thumbnail file not found'),
                        const SizedBox(height: 16),
                      ],
                    if (_thumbnailData != null) ...
                      [
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text('Local Thumbnail Data:', style: TextStyle(fontWeight: FontWeight.bold)),
                        ),
                        Image.memory(
                          _thumbnailData!,
                          height: 200,
                          fit: BoxFit.contain,
                        ),
                        const SizedBox(height: 16),
                      ],
                    if (_networkThumbnailPath != null) ...
                      [
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text('Network Thumbnail File:', style: TextStyle(fontWeight: FontWeight.bold)),
                        ),
                        if (File(_networkThumbnailPath!).existsSync())
                          Image.file(
                            File(_networkThumbnailPath!),
                            height: 200,
                            fit: BoxFit.contain,
                          )
                        else
                          const Text('Network thumbnail file not found'),
                        const SizedBox(height: 16),
                      ],
                    if (_networkThumbnailData != null) ...
                      [
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text('Network Thumbnail Data:', style: TextStyle(fontWeight: FontWeight.bold)),
                        ),
                        Image.memory(
                          _networkThumbnailData!,
                          height: 200,
                          fit: BoxFit.contain,
                        ),
                        const SizedBox(height: 16),
                      ],
                    if (_thumbnailPath == null && _thumbnailData == null && _networkThumbnailPath == null && _networkThumbnailData == null)
                      const Padding(
                        padding: EdgeInsets.all(32.0),
                        child: Text(
                          '缩略图将在这里显示',
                          style: TextStyle(color: Colors.grey, fontSize: 16),
                          textAlign: TextAlign.center,
                        ),
                      ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // 视频源选择
                    const Text('视频源选择:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    
                    // 本地视频选择
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            const Text('本地视频:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                            const SizedBox(height: 8),
                            ElevatedButton(
                              onPressed: _isLoading ? null : _selectVideo,
                              child: const Text('选择本地视频'),
                            ),
                            if (_selectedVideoPath != null && _selectedVideoPath!.isNotEmpty)
                              Padding(
                                padding: const EdgeInsets.only(top: 8.0),
                                child: Text(
                                  '已选择: ${_selectedVideoPath!.split('/').last}',
                                  style: const TextStyle(fontSize: 12, color: Colors.grey),
                                ),
                              ),
                          ],
                        ),
                      ),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 网络视频输入
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            const Text('网络视频:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                            const SizedBox(height: 8),
                            TextField(
                              controller: _networkUrlController,
                              decoration: const InputDecoration(
                                labelText: '网络视频URL',
                                hintText: '输入视频URL (例如: http://example.com/video.mp4)',
                                border: OutlineInputBorder(),
                              ),
                              enabled: !_isLoading,
                            ),
                          ],
                        ),
                      ),
                    ),
                    
                    const SizedBox(height: 24),
                    
                    // 统一的生成按钮
                    const Text('生成缩略图:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    
                    ElevatedButton.icon(
                      onPressed: _canGenerateThumbnail() ? _generateThumbnail : null,
                      icon: const Icon(Icons.image),
                      label: const Text('生成缩略图'),
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        textStyle: const TextStyle(fontSize: 16),
                      ),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 单独的功能测试按钮
                    const Text('单独功能测试:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ElevatedButton(
                          onPressed: (_selectedVideoPath != null && !_isLoading) ? _generateThumbnailFile : null,
                          child: const Text('本地文件'),
                        ),
                        ElevatedButton(
                          onPressed: (_selectedVideoPath != null && !_isLoading) ? _generateThumbnailData : null,
                          child: const Text('本地数据'),
                        ),
                        ElevatedButton(
                          onPressed: (_networkUrlController.text.trim().isNotEmpty && !_isLoading) ? _generateNetworkThumbnailFile : null,
                          child: const Text('网络文件'),
                        ),
                        ElevatedButton(
                          onPressed: (_networkUrlController.text.trim().isNotEmpty && !_isLoading) ? _generateNetworkThumbnailData : null,
                          child: const Text('网络数据'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
